package com.micro.train.service;

import com.micro.train.service.impl.TrainSeatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * 库存管理定时任务服务
 * 自动清理过期的库存记录
 */
@Service
public class InventoryScheduleService {

    @Autowired
    private TrainSeatServiceImpl trainSeatService;

    /**
     * 每天凌晨2点执行库存清理任务
     * 清理7天前的过期库存记录
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanupExpiredInventory() {
        try {
            LocalDate expireDate = LocalDate.now().minusDays(7);
            trainSeatService.cleanupExpiredInventory(expireDate);
            System.out.println("定时任务 - 清理过期库存完成，过期日期: " + expireDate);
        } catch (Exception e) {
            System.err.println("定时任务 - 清理过期库存失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 每天凌晨3点执行库存窗口滚动任务
     * 为所有列车初始化新的7天库存窗口
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void rollInventoryWindow() {
        try {
            LocalDate newBaseDate = LocalDate.now();
            trainSeatService.rollInventoryWindow(newBaseDate);
            System.out.println("定时任务 - 库存窗口滚动完成，新基准日期: " + newBaseDate);
        } catch (Exception e) {
            System.err.println("定时任务 - 库存窗口滚动失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
